package com.tjl.warehouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tjl.warehouse.common.ErrorCode;
import com.tjl.warehouse.common.R;
import com.tjl.warehouse.constant.UserConstanat;
import com.tjl.warehouse.exception.BusinessException;
import com.tjl.warehouse.exception.ThrowUtils;
import com.tjl.warehouse.model.MyPage;
import com.tjl.warehouse.model.Role;
import com.tjl.warehouse.model.UserInfo;
import com.tjl.warehouse.model.UserRole;
import com.tjl.warehouse.model.dto.AssignRoleReq;
import com.tjl.warehouse.service.RoleService;
import com.tjl.warehouse.service.UserInfoService;
import com.tjl.warehouse.mapper.UserInfoMapper;
import com.tjl.warehouse.service.UserRoleService;
import com.tjl.warehouse.utils.DigestUtil;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
* @author Tang
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2024-05-10 19:26:22
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Resource
    private UserInfoMapper userMapper;
    @Resource
    RoleService roleService;
    @Resource
    UserRoleService userRoleService;

    @Override
    public UserInfo login(String userCode, String userPwd) {

        var userQuery = new LambdaQueryWrapper<UserInfo>();
        userQuery.eq(UserInfo::getUserCode, userCode)
                .eq(UserInfo::getUserPwd, DigestUtil.hmacSign(userPwd));
        var userInfo = userMapper.selectOne(userQuery);
        ThrowUtils.throwIf(userInfo == null, ErrorCode.LOGIN_ERROR);
        //检查是否审核
        if (Objects.equals(userInfo.getUserState(), UserConstanat.USER_STATE_NOT_PASS)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"用户未审核");
        }

        return userInfo;
    }

    @Override
    public MyPage<UserInfo> getUserPage(UserInfo userInfo, MyPage<UserInfo> myPage) {

        LambdaQueryWrapper<UserInfo> query = new LambdaQueryWrapper<>();
        //模糊查询
        query.like(StringUtils.isNotBlank(userInfo.getUserCode()), UserInfo::getUserCode, userInfo.getUserCode())
                .like(StringUtils.isNotBlank(userInfo.getUserName()), UserInfo::getUserName, userInfo.getUserName())
                .like(StringUtils.isNotBlank(userInfo.getUserType()), UserInfo::getUserType, userInfo.getUserType())
                .eq(userInfo.getUserState() != null, UserInfo::getUserState, userInfo.getUserState());

        IPage<UserInfo> userInfoIPage = userMapper.selectPage(myPage.toPage(), query);
        myPage.setTotalNum(userInfoIPage.getTotal());
        myPage.setPageNum(userInfoIPage.getCurrent());
        myPage.setPageCount(userInfoIPage.getPages());
        myPage.setPageSize(userInfoIPage.getSize());
        myPage.setResultList(userInfoIPage.getRecords());
        return myPage;
    }

    @Override
    public boolean updateUserRole(AssignRoleReq assignRole) {
        //检查用户是否存在
        if(!isExist(assignRole.getUserId(),assignRole.getUserCode())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在");
        }

        //如果什么角色都没选 清空用户所有角色
        if (assignRole.getRoleCheckList().isEmpty()){
            roleService.deleteAllRole(assignRole.getUserId());
            return true;
        }

        //获取本次需要添加的权限id
        List<Role> roleList = roleService.getRoleList();

        //获取选择的角色id
        List<Integer> allUpdateRoleIds = roleList.stream()
                .filter(role -> assignRole.getRoleCheckList().contains(role.getRoleName()))
                .map(Role::getRoleId)
                .toList();

        //获取用户已有的角色id 如果已经保存有的角色不重复保存
        var queryUserRole = new LambdaQueryWrapper<UserRole>();
        queryUserRole.eq(UserRole::getUserId, assignRole.getUserId());
        List<UserRole> userRoleExistList = userRoleService.list(queryUserRole);
        //排除 已经保存的权限 得到最终需要添加的id
        List<Integer> updateRoleIds = allUpdateRoleIds.stream()
                .filter(roleId -> userRoleExistList.stream()
                    .noneMatch(userRole -> userRole.getRoleId().equals(roleId)))
                .toList();

        //添加角色
        boolean isOk = userRoleService.saveBatch(updateRoleIds.stream()
                .map(roleId -> {
                    UserRole userRole = new UserRole();
                    userRole.setRoleId(roleId);
                    userRole.setUserId(assignRole.getUserId());
                    return userRole;
                }).toList());

        return isOk;
    }

    @Override
    public boolean addUser(UserInfo userInfo,Integer createBy) {

        if (StringUtils.isBlank(userInfo.getUserCode())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户编码不能为空");
        }
        if (StringUtils.isBlank(userInfo.getUserName())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名称不能为空");
        }
        if (StringUtils.isBlank(userInfo.getUserPwd())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码不能为空");
        }

        if (userMapper.selectOne(new QueryWrapper<UserInfo>()
                .eq("user_code",userInfo.getUserCode())) != null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号已存在");
        }

        // 默认新增用户状态为正常
        userInfo.setIsDelete("0");
        //默认未审核状态
        userInfo.setUserState("0");
        //加密密码
        userInfo.setUserPwd(DigestUtil.hmacSign(userInfo.getUserPwd()));
        userInfo.setCreateBy(createBy);
        int insert = userMapper.insert(userInfo);
        return insert > 0;
    }

    @Override
    public boolean updateUser(UserInfo userInfo,Integer updateBy) {
        ThrowUtils.throwIfParams(userInfo == null);
        ThrowUtils.throwIfParams(userInfo.getUserId() == null, "用户id不能为空");

        //修改密码
        if (StringUtils.isNotBlank(userInfo.getUserPwd())){
            userInfo.setUserPwd(DigestUtil.hmacSign(userInfo.getUserPwd()));
        }

        userInfo.setUpdateBy(updateBy);
        int i = userMapper.updateById(userInfo);

        return i > 0;
    }

    @Override
    public boolean isExist(Integer userId, String userCode) {
        var query = new LambdaQueryWrapper<UserInfo>();
        query.eq(UserInfo::getUserId, userId).eq(UserInfo::getUserCode, userCode);
        return userMapper.exists(query);
    }
}




